package com.sita.tboard.advertisement;

import android.os.SystemClock;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.sita.bike.rest.model.Advertisement;
import com.sita.bike.rest.model.AdvertisementParams;
import com.sita.bike.rest.model.AdvertisementResponse;
import com.sita.bike.support.Constants;
import com.sita.bike.support.GlobalContext;
import com.sita.bike.utils.LocalStorage;
import com.sita.tboard.ui.tools.L;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.picasso.Picasso;

import java.util.concurrent.TimeUnit;

import retrofit.Callback;
import retrofit.RequestInterceptor;
import retrofit.RestAdapter;
import retrofit.RetrofitError;
import retrofit.client.OkClient;
import retrofit.client.Response;
import retrofit.converter.GsonConverter;
import retrofit.http.Body;
import retrofit.http.POST;

/**
 * Created by xiaodong on 16/3/5.
 */
public class AdvertiseManager {

    public enum AppState {
        FROM_LAUNCH,
        IN_FOREGROUND,
        IN_BACKGROUND,
        IN_CAMERA_PHOTO
    }

    interface AdvertisementService {
        @POST("/tinterest/v1/advertisinges/getone")
        void getAdvertisementData(@Body AdvertisementParams request, Callback<AdvertisementResponse> callback);
    }

    private static class AdvertiseManagerHolder {
        private static final AdvertiseManager INSTANCE = new AdvertiseManager();
    }

    private AdvertiseManager() {
    }

    public static final AdvertiseManager getInstance() {
        return AdvertiseManagerHolder.INSTANCE;
    }

    private AdModel adModel;

    private Long preAdShowTime;

    private boolean canAdShow;

    private AppState appState = AppState.FROM_LAUNCH;
    private AppState prevState = AppState.FROM_LAUNCH;

    public AppState getAppState() {
        return appState;
    }

    public AppState getPrevState() {
        return prevState;
    }

    public boolean canAdShow() {
        if (prevState == AppState.FROM_LAUNCH) {
            return true;
        }
        if (preAdShowTime == null) {
            return true;
        }
        if (canAdShow) {
            if (prevState != AppState.IN_CAMERA_PHOTO && prevState == AppState.IN_BACKGROUND) {
                long currTime = SystemClock.elapsedRealtime();
                if (currTime >= (preAdShowTime.longValue() + AdvertisePolicy.INTERVAL)) {
                    return true;
                }
            }
        }
        return false;
    }

    public void setAdShow(boolean show) {
        canAdShow = show;
    }

    public void setPreAdShowTime(long preAdShowTime) {
        this.preAdShowTime = preAdShowTime;
    }

    public void setAppState(AppState mAppState) {
        prevState = appState;
        appState = mAppState;
    }

    public AdModel getAdModel() {
        if (adModel == null) {
            adModel = LocalStorage.getAdModel();
        }
        return adModel;
    }

    public void decreasePlayCount() {
        if (adModel != null) {
            adModel.playCount -= 1;
            LocalStorage.setAdModel(adModel);
        }
    }

    public void downloadAdvertise() {
        final OkHttpClient okHttpClient = new OkHttpClient();
        okHttpClient.setReadTimeout(60, TimeUnit.SECONDS);
        okHttpClient.setConnectTimeout(60, TimeUnit.SECONDS);
        okHttpClient.setWriteTimeout(120, TimeUnit.SECONDS);

        Gson gson = new GsonBuilder()
                .setDateFormat("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'SSS'Z'")
                .serializeNulls()
                .create();

        RequestInterceptor restInterceptor = new RequestInterceptor() {
            @Override
            public void intercept(RequestFacade request) {
                request.addHeader("Content-Type", Constants.APPLICATION_JSON);
                request.addHeader("Accept", Constants.APPLICATION_JSON);
            }
        };

        RestAdapter restAdapter = new RestAdapter.Builder()
                .setLogLevel(RestAdapter.LogLevel.FULL)
                .setEndpoint(Constants.BASE_URI)
                .setConverter(new GsonConverter(gson))
                .setRequestInterceptor(restInterceptor)
                .setClient(new OkClient(okHttpClient))
                .build();

        AdvertisementService adService = restAdapter.create(AdvertisementService.class);

        adService.getAdvertisementData(new AdvertisementParams(), new Callback<AdvertisementResponse>() {
            @Override
            public void success(AdvertisementResponse adResponse, Response response) {
                if (!adResponse.mErrorCode.equals("0")) {
                    return;
                }
                Advertisement advertisement = adResponse.mData;
                adModel = LocalStorage.getAdModel();
                if (adModel == null || !adModel.id.equals(String.valueOf(advertisement.id))) {
                    int playCount = advertisement.playcount != null ? Integer.valueOf(advertisement.playcount) : 10;
                    Picasso.with(GlobalContext.getGlobalContext()).load(advertisement.picurl).fetch();

                    adModel = new AdModel(String.valueOf(advertisement.id),
                            advertisement.picurl, advertisement.adurl, playCount);

                    LocalStorage.setAdModel(adModel);
                }
            }

            @Override
            public void failure(RetrofitError error) {
                L.e(error);
            }
        });
    }
}
